<template>
  <div>
    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-cell title="历史产品录入界面" value size="large" />
      </van-cell-group>

      <van-field
        :required="true"
        v-model="form.customerName"
        name="客户名称"
        label="客户名称"
        placeholder="请输入客户名称"
        :rules="[{ required: true, message: '请填写客户名称' }]"
      />
      <van-field
        :required="true"
        v-model="form.siteName"
        name="站点名称"
        label="站点名称"
        placeholder="请输入站点名称"
        :rules="[{ required: true, message: '请输入站点名称' }]"
      />
      <van-field
        autosize
        :required="true"
        v-model="form.siteAddress"
        name="站点地址"
        label="站点地址"
        :disabled="true"
        placeholder="请输入站点地址"
        :rules="[{ required: true, message: '请输入站点地址' }]"
      >
        <template #input>
          <textarea
            v-model="form.siteAddress"
            placeholder="请输入站点地址"
            class="custom-textarea"
            style="width: 100%; height: 80px;"
          ></textarea>
        </template>
      </van-field>
      <van-field
        :required="true"
        v-model="form.siteManager"
        name="站点负责人"
        label="站点负责人"
        placeholder="请输入站点负责人"
        :rules="[{ required: true, message: '请输入站点负责人' }]"
      />
      <van-field
        :required="true"
        v-model="form.contactInformation"
        name="联系方式"
        label="联系方式"
        placeholder="请输入联系方式"
        :rules="[{ required: true, message: '请输入联系方式' }]"
      />

      <van-field
        readonly
        :required="true"
        name="picker"
        :value="form.yardType"
        label="场站类型"
        placeholder="请选择场站类型"
        @click="showPicker = true"
        :rules="[{ required: true, message: '请选择场站类型' }]"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onyardType"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        :required="true"
        v-model="form.quantity"
        type="number"
        name="站内充电桩数量"
        label="站内充电桩数量"
        placeholder="请输入站内充电桩数量"
        :rules="[{ required: true, message: '请输入站内充电桩数量' }]"
      />

      <van-field
        :required="true"
        readonly
        name="picker"
        :value="form.module"
        label="模块"
        placeholder="请选择模块"
        @click="PickerModule = true"
        :rules="[{ required: true, message: '请输入模块' }]"
      />
      <van-popup v-model="PickerModule" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsModule"
          @confirm="onyardTypeModule"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        :required="true"
        readonly
        name="picker"
        :value="form.moduleSpec"
        label="模块规格"
        placeholder="请选择模块规格"
        @click="PickerModuleSpec = true"
        :rules="[{ required: true, message: '请输入模块规格' }]"
      />
      <van-popup v-model="PickerModuleSpec" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsModuleSpec"
          @confirm="onyardTypeModuleSpec"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        :required="true"
        readonly
        name="屏幕"
        :value="form.screen"
        label="屏幕"
        placeholder="请输入屏幕"
        @click="PickerScreen = true"
        :rules="[{ required: true, message: '请输入屏幕' }]"
      />
      <van-popup v-model="PickerScreen" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsScreen"
          @confirm="onyardTypeScreen"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        :required="true"
        readonly
        name="picker"
        :value="form.screenSpec"
        label="屏幕规格"
        placeholder="请选择屏幕规格"
        @click="PickerScreenSpec = true"
        :rules="[{ required: true, message: '请输入屏幕规格' }]"
      />
      <van-popup v-model="PickerScreenSpec" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsScreenSpec"
          @confirm="onyardTypeScreenSpec"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        :required="true"
        v-model="form.backstage"
        name="后台"
        label="后台"
        placeholder="请输入后台"
        :rules="[{ required: true, message: '请输入后台' }]"
      />

      <van-field
        :required="true"
        readonly
        clickable
        name="巡检时间"
        :value="form.inspectionTime"
        label="巡检时间"
        placeholder="点击选择巡检时间"
        @click="showPopup2"
        :rules="[{ required: true, message: '请输入巡检时间' }]"
      />
      <van-popup v-model="inspection.pickerShow" position="bottom" :style="{ height: '30%' }">
        <van-datetime-picker
          @confirm="confirm2"
          @cancel="cancellation"
          v-model="inspection.Time"
          type="datetime"
          title="选择巡检时间"
          :min-date="inspection.minDate"
          :max-date="inspection.maxDate"
        />
      </van-popup>

      <van-field
        :required="true"
        name="softwareVersion"
        label="软件版本"
        :rules="[{ required: true, message: '请上传软件版本' }]"
      >
        <template #input>
          <van-uploader v-model="softwareVersion" :after-read="afterReadVersion" :max-count="1" />
        </template>
      </van-field>

      <van-field
        :required="true"
        v-model="form.snCode"
        name="SN码"
        label="SN码"
        placeholder="请输入SN码"
        :rules="sncode"
      />

      <van-field
        :required="true"
        name="snCodePhotograph"
        label="sn码图片"
        :rules="[{ required: true, message: '请上传sn码图片' }]"
      >
        <template #input>
          <van-uploader v-model="snCodePhotograph" :after-read="afterReadSnCode" :max-count="1" />
        </template>
      </van-field>

      <van-field
        :required="true"
        v-model="form.znCode"
        name="ZN码/资产码"
        label="ZN码/资产码"
        placeholder="请输入ZN码/资产码"
        :rules="[{ required: true, message: '请输入ZN码/资产码' }]"
      />

      <van-field
        :required="true"
        name="znCodePhotograph"
        label="ZN码照片"
        :rules="[{ required: true, message: '请上传ZN码照片' }]"
      >
        <template #input>
          <van-uploader v-model="znCodePhotograph" :after-read="afterReadZnCode" :max-count="1" />
        </template>
      </van-field>

      <van-field v-model="form.remark" name="备注" label="备注" placeholder="请输入备注" />

      <van-field
        :required="true"
        v-model="form.createBy"
        name="录入人"
        label="录入人"
        placeholder="请输入录入人"
        :rules="[{ required: true, message: '请输入录入人' }]"
      />

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
// <script type="text/javascript">
//     window._AMapSecurityConfig = {
//         securityJsCode:'c2ab06c241e649104225082d1dd3d097',
//     }
//
</script>
// <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=ea7a5d156e67765574afec4a64c2e7f6&AMap.Geolocation"></script>

<script>
import {
  searchHistorical,
  fileUpload,
  UpdataHistorical
} from "@/api/productEntry/index";
import moment from "moment";
export default {
  data() {
    return {
      //软件版本
      softwareVersion: [],
      //sn图片
      snCodePhotograph: [],
      //ZN图片
      znCodePhotograph: [],
      form: {
        customerName: "", //客户名称
        siteName: "", //站点名称
        siteAddress: "", //站点地址
        siteManager: "", //站点负责人
        contactInformation: "", //联系方式
        yardType: "", //场站类型
        quantity: "", //充电桩数量
        module: "", //模块
        moduleSpec: "", //模块 规格
        screen: "", //屏幕
        screenSpec: "", //屏幕 规格
        backstage: "", //后台
        inspectionTime: "", //巡检时间
        softwareVersion: "", //软件版本 [{ url: 'https://img01.yzcdn.cn/vant/leaf.jpg' }],
        snCode: "", //sn码
        snCodePhotograph: "", //sn码图片
        znCode: "", //ZN码
        znCodePhotograph: "", //zn码图片
        remark: "", //备注
        createBy: "" //录入人
      },
      //是否展示场站类型
      showPicker: false,
      //是否展示模块
      PickerModule: false,
      //是否展示模块规格
      PickerModuleSpec: false,
      //是否展示屏幕
      PickerScreen: false,
      //是否展示屏幕规格
      PickerScreenSpec: false,
      //场站类型
      columns: ["公交", "自营", "运营商"],
      //模块list
      columnsModule: [
        "核达",
        "英飞源",
        "英可瑞",
        "麦格米特",
        "世纪汇能",
        "优优绿能",
        "中兴",
        "通合",
        "凌康"
      ],
      //模块规格 list
      columnsModuleSpec: [],
      //屏幕list
      columnsScreen: ["迪文", "威纶通", "昆仑通态", "拓普威", "欣瑞达"],
      //屏幕规格 list
      columnsScreenSpec: [],
      //校验sn码长度
      sncode: [
        { required: true, message: "sn码不能为空!" },
        {
          validator: val => {
            return /^[A-Za-z0-9!@#$%^&*()_+{}\[\]:;<>,.?\~\\-]{13}$/.test(val);
          },
          message: "请输入13位sn码"
        }
      ],
      //巡检
      inspection: {
        Time: new Date(), //巡检时间显示
        pickerShow: false,
        minDate: new Date(2020, 0, 1),
        maxDate: new Date(2025, 10, 1)
      }
    };
  },
  created() {
    // 获取当前时间
    const currentDate = new Date();
    // 使用Moment.js格式化时间给巡检时间赋值
    this.form.inspectionTime = moment(currentDate).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    this.MapLoader();
  },
  methods: {
    //提交按钮
    onSubmit(values) {
      console.log(values, "values");
      if (
        this.form.znCodePhotograph == "" ||
        this.form.snCodePhotograph == "" ||
        this.form.softwareVersion == ""
      ) {
        this.$modal.msgError("网络异常,图片上传失败");
        return;
      }
      if (this.form.moduleSpec == "其他" || this.form.screenSpec == "其他") {
        if (this.form.remark == "") {
          this.$modal.msgError("请在备注中输入规格");
          return;
        }
      }
      searchHistorical(this.form).then(res => {
        if (res.msg == "sn码已存在") {
          this.$dialog.confirm({
              title: "更新提示",
              message: "SN码已在数据库存在,是否更新?"
            }).then(() => {
              //需要调修改接口
              console.log("确认");
              this.Updata(this.form);
            })
            .catch(() => {
              console.log("取消");
            });
        } else {
          this.$dialog.confirm({
              title: "更新提示",
              message: "确认是否提交?"
            }) .then(() => {
              this.Updata(this.form);
            })
            .catch(() => {
              console.log("取消");
            });
        }
      });
    },
    //修改接口
    Updata(form) {
      UpdataHistorical(form).then(res => {
        console.log(res, "修改接口");
        if (res.code == 200) {
          this.$toast(res.msg);
          this.rest();
        }
      });
    },
    //场站选择change事件
    onyardType(value) {
      this.form.yardType = value;
      this.showPicker = false;
    },
    //模块选择change事件
    onyardTypeModule(value) {
      console.log(value, "value");
      //给模块赋值
      this.form.module = value;
      //给模块 规格 置空
      this.form.moduleSpec = "";
      if (this.form.module == "核达") {
        this.columnsModuleSpec = [
          "AD153M750-1M1;15KW/DC250~750V",
          "AD153M750-1M1C",
          "AD153M450-1M1",
          "A701G AD153M450-1M1",
          "AD153M750-1M1;15KW/DC250~750V(A701D新国标)",
          "AD153M750-1M1F",
          "AD153M750-1M4B",
          "其他"
        ];
      } else if (this.form.module == "英飞源") {
        this.columnsModuleSpec = [
          "REG75033",
          "REG75033F1",
          "REG75025",
          "REG50040",
          "REG75040F1",
          "REG75050",
          "REG75030G(15KW 150-750V 0-25A )",
          "REG50050",
          "REG1K025G",
          "REG1K0100G",
          "REG1K0100",
          "CEG75050",
          "REG1K0100G",
          "REG75060A",
          "REG75050A",
          "REG1K070-1000V-67A-20kW",
          "BEG1K075-1000V-73A-22kW(双向)",
          "REG1K0135-1000V-135A-40KW",
          "REG1K0100A2-1000V-100A-30KW",
          "REG75060A",
          "其他"
        ];
      } else if (this.form.module == "英可瑞") {
        this.columnsModuleSpec = ["EVR600-15000C", "EVR100-10000", "其他"];
      } else if (this.form.module == "麦格米特") {
        this.columnsModuleSpec = [
          "MR450-3000HK",
          "MR700-3000HK",
          "MR450-3000ZR",
          "其他"
        ];
      } else if (this.form.module == "世纪汇能") {
        this.columnsModuleSpec = [
          "SJD750-15KA",
          "SJD750-15KB",
          "SJD750-15KB(H)",
          "SJD750-22KA",
          "SJD750-15KA",
          "其他"
        ];
      } else if (this.form.module == "优优绿能") {
        this.columnsModuleSpec = [
          "UR100030SW-CE",
          "UR100020SW-CE",
          "UR100020-SW(20KW 200~1000V 20A U )",
          "UR100030-SW(30KW 200~1000V 30A U 灌胶)",
          "UR100030-SW(30KW 200~1000V 30A U)",
          "UR100040-SW(40KW 200~1000V 40A U)",
          "其他"
        ];
      } else if (this.form.module == "中兴") {
        this.columnsModuleSpec = [
          "ZXD030 T751",
          "ZXD020 T751_V3.0",
          "ZXD020 T102(V3.0R01)",
          "ZXD020 T102 V3.0E （欧标）",
          "ZXD020 T102 V3.0H(20KW 200-1000V 66.7A Z )",
          "ZXD030 T751",
          "ZXD020 T102(V3.0R01)（中兴）",
          "ZXNE D030 T751 V2.3/750V/20KW/V2G/中兴",
          "ZXD030 T102 V3.0R1(30KW 200-1000V 100A Z)",
          "ZXD020 T102(V3.0R01)/200-750V/66A/Z/取消风道堵塞保护/模块表面贴标签区分标准品",
          "其他"
        ];
      } else if (this.form.module == "通合") {
        this.columnsModuleSpec = ["TH750Q61ND-AX-750V-67A-20KW", "其他"];
      } else if (this.form.module == "凌康") {
        this.columnsModuleSpec = ["R1K060G6-1000V-67A-20KW", "其他"];
      }

      this.PickerModule = false;
    },
    //模块 规格 选择change事件
    onyardTypeModuleSpec(value) {
      console.log(value, "value");
      this.form.moduleSpec = value;
      this.PickerModuleSpec = false;
    },
    //屏幕选择change事件
    onyardTypeScreen(value) {
      //给屏幕赋值
      this.form.screen = value;
      //给模块 规格 置空
      this.form.screenSpec = "";
      if (this.form.screen == "迪文") {
        this.columnsScreenSpec = [
          "DMT80480T070_16WT",
          "DMT80480T070_16WTZ11",
          "DMT80480T070_16WTZ22(带配件:金属卡扣M02630)",
          "DMT80600T080",
          "DMT48270C043-15WTZ1",
          "其他"
        ];
      } else if (this.form.screen == "威纶通") {
        this.columnsScreenSpec = [
          "TK6070IH",
          "TK6070iQL,常温屏",
          "TK6070iQL,宽温屏",
          "其他"
        ];
      } else if (this.form.screen == "昆仑通态") {
        this.columnsScreenSpec = [
          "TPC1061Ti",
          "TPC7062KX",
          "MT8100iE1",
          "MT8101iE1",
          "TPC7062TX",
          "TPC7062KT",
          "其他"
        ];
      } else if (this.form.screen == "拓普威") {
        this.columnsScreenSpec = [
          "LMT070DICFWD-AKA",
          "LMT070DICFWD-AKE （单枪板屏）",
          "LMT070DICFWD-AKE-1 （双枪板屏）",
          "LMT070DICFWD-NLD",
          "其他"
        ];
      } else if (this.form.screen == "欣瑞达") {
        this.columnsScreenSpec = [
          "XG070YTD14R",
          "XT070YTA14R-HK",
          "XT070YTA23R",
          "其他"
        ];
      }
      this.PickerScreen = false;
    },
    //屏幕规格选择 change事件
    onyardTypeScreenSpec(value) {
      this.form.screenSpec = value;
      this.PickerScreenSpec = false;
    },
    //软件版本 文件上传
    afterReadVersion(file) {
      console.log(file, "file");
      var formdata = new FormData();
      formdata.append("file", file.file);
      fileUpload(formdata).then(res => {
        console.log(res, "软件版本rss.data.url");
        if (res.code == 200) {
          this.form.softwareVersion = res.data.url;
          this.$modal.msgSuccess(res.msg);
        }
      });
    },
    //sn图片上传
    afterReadSnCode(file) {
      console.log(file, "file");
      var formdata = new FormData();
      formdata.append("file", file.file);
      fileUpload(formdata).then(res => {
        console.log(res, "SNrss.data.url");
        if (res.code == 200) {
          this.form.snCodePhotograph = res.data.url;
          this.$modal.msgSuccess(res.msg);
        }
      });
    },
    //ZN图片上传
    afterReadZnCode(file) {
      console.log(file, "file");
      var formdata = new FormData();
      formdata.append("file", file.file);
      fileUpload(formdata).then(res => {
        console.log(res, "ZNrss.data.url");
        if (res.code == 200) {
          this.form.znCodePhotograph = res.data.url;
          this.$modal.msgSuccess(res.msg);
        }
      });
    },
    //清空数据
    rest() {
      //后台
      (this.form.backstage = ""),
        //软件版本
        (this.softwareVersion = []);
      //软件版本
      (this.form.softwareVersion = ""),
        //sn码 图片
        (this.snCodePhotograph = []),
        //sn码
        (this.form.snCode = ""),
        //sn码照片
        (this.form.snCodePhotograph = ""),
        //zn码
        (this.form.znCode = ""),
        //zn码 图片
        (this.znCodePhotograph = []),
        //zn码照片
        (this.form.znCodePhotograph = ""),
        //备注
        (this.form.remark = "");
    },

    //结束时间确定
    confirm2() {
      this.inspection.pickerShow = false; //弹出框隐藏
      //巡检时间的值
      this.form.inspectionTime = moment(this.inspection.Time).format(
        "YYYY-MM-DD HH:mm:ss"
      );
    },
    //巡检时间弹出层
    showPopup2() {
      this.inspection.pickerShow = true; //弹出框显示
    },
    //巡检时间取消按钮
    cancellation() {
      this.inspection.pickerShow = false; //弹出框隐藏
    },

    MapLoader() {
      let that = this;
      let aMapScript = document.createElement("script");
      // "https://webapi.amap.com/maps?v=1.4.11&key=&plugin=AMap.CitySearch"
      aMapScript.setAttribute(
        "src",
        "https://webapi.amap.com/maps?v=1.4.15&key=ea7a5d156e67765574afec4a64c2e7f6&AMap.Geolocation"
      );
      document.head.appendChild(aMapScript);
      window._AMapSecurityConfig = {
        securityJsCode: "c2ab06c241e649104225082d1dd3d097"
      };
      return (aMapScript.onload = function() {
        // mapObj = new AMap.Map('iCenter');
        AMap.plugin("AMap.Geolocation", function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: "RB",
            extensions: "all",
            needAddress: true
          });

          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, "complete", onComplete);
          AMap.event.addListener(geolocation, "error", onError);
          function onComplete(data) {
            // data是具体的定位信息
            console.log(data, "=======data==========");
            let lng = data.position.lng;
            console.log(data.position.lng, "=======lng====");
            let lat = data.position.lat;
            let lnglatXY = [lng, lat];
            let xy = lnglatXY.join(",");
            // that.init(lnglatXY);
            that.form.siteAddress = data.formattedAddress + `(${xy})`;
            console.log("123123");
          }

          function onError(data) {
            console.log(data);
            console.log("定位出错");
            that.$toast("获取地址失败！！！");
            // 定位出错
          }
        });
      });
    },

    init(lnglatXY) {
      let xy = lnglatXY.join(",");
      let url = `https://restapi.amap.com/v3/geocode/regeo?key=8a6140378cfc5a0d759bd042a623c89a&location=${xy}&extensions=all`;
      // console.log(xy, aMapScriptq, "======xy=======");
      fetch(url)
        .then(response => response.json())
        .then(data => {
          console.log(data, "=====data=====");
          this.form.siteAddress = data.regeocode.formatted_address + `(${xy})`;
        });
    }
  }
};
</script>

<style >
.custom-textarea {
  white-space: normal;
  resize: none;
}
</style>